package per.ethan.cloud.consumer.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import per.ethan.cloud.consumer.service.PaymentService;

/**
 * @author Ethan
 * @date 2020/04/09 12:37
 */
@RestController
@RequestMapping("/order")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class ConsumerController {

    private final RestTemplate restTemplate;

    private final PaymentService paymentService;

    private static final String CLOUD_PROVIDER = "http://cloud-alibaba-provider";

    @GetMapping(value = "/getPort")
    public String getPort() {
        return restTemplate.getForObject(CLOUD_PROVIDER + "/payment/getPort", String.class);
    }

    @GetMapping(value = "/fallbackOrder")
    // @SentinelResource(value = "fallbackOrder", fallback = "handlerFallback") // java业务异常
    // @SentinelResource(value = "fallbackOrder", blockHandler = "handlerBlock") // sentinel配置违规
    @SentinelResource(value = "fallbackOrder", fallback = "handlerFallback",
            blockHandler = "handlerBlock", exceptionsToIgnore = {ArithmeticException.class})  // 两个都配以sentinel规则为主
    public String fallbackOrder() {
        return restTemplate.getForObject(CLOUD_PROVIDER + "/payment/fallbackPayment", String.class);
    }

    public String handlerFallback(Throwable e) {
        return "handlerFallback: " + e.getMessage();
    }

    public String handlerBlock(BlockException e) {
        return "handlerBlockException: " + e.getMessage();
    }

    @GetMapping(value = "/fallbackOrder2")
    public String fallbackOrder2() {
        return paymentService.fallbackProvider();
    }

}
